package com.huffman.smart_picture.interceptor;

import com.huffman.smart_picture.common.auth.SessionContext;
import com.huffman.smart_picture.common.auth.annotation.CheckRole;
import com.huffman.smart_picture.common.auth.annotation.LoginRequired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author DengLin
 * @title 服务拦截器
 * @date 2024/06/29
 */
@Component
public class ServiceInterceptor implements HandlerInterceptor {

    @Resource
    private SessionContext sessionContext;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
        CheckRole checkRole = method.getAnnotation(CheckRole.class);
        if (Objects.nonNull(loginRequired) || Objects.nonNull(checkRole)) {
            HttpSession session = request.getSession();
            sessionContext.addSession(session);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        sessionContext.removeSession();
    }


}
